package com.baixun.gasadmin.controller;

import com.baixun.gascommon.utils.R;
import com.baixun.gasentity.dto.*;
import com.baixun.gasentity.entity.SysVideoMessage;
import com.baixun.gasentity.vo.AbnormalPointVo;
import com.baixun.gasentity.vo.AiAlarmVO;
import com.baixun.gasentity.vo.VideoPlaybackVO;
import com.baixun.gassystem.service.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @program: 上海燃气驾驶舱
 * @description: 视频监控控制层
 * @author: yesong
 **/
@RestController
@RequestMapping("/admin")
@Api(tags = "视频监控")
public class AdminController {

    @Autowired
    private AiAlarmService aiAlarmService;
    @Autowired
    private AlarmService alarmService;
    @Autowired
    public SysVideoMessageService sysVideoMessageService;

    @Autowired
    private AbnormalPointService abnormalPointService;

    @Autowired
    private SysMonitorStatisticsService sysMonitorStatisticsService;

    @Autowired
    private VideoPlaybackService videoPlaybackService;

    @Autowired
    private HomePageService homePageService;

//    @Autowired
//    private SysDataPermissionService dataPermissionService;


    //等evs回调
    @ApiOperation(value = "获取指定时间段内的报警数据")
    @GetMapping("/alarm-counts")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R<AiAlarmVO> getAlarmCounts(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {

        // 封装请求参数为 DTO
        AiAlarmDTO aiAlarmDTO = new AiAlarmDTO(startDate, endDate);

        // 调用 Service 传递 DTO
        AiAlarmVO alarmCounts = aiAlarmService.getAlarmCounts(aiAlarmDTO);
        // 使用R.success()返回响应
        return R.success(alarmCounts);
    }

    //报警列表实时监控
    @ApiOperation(value = "获取报警列表是实时监控", notes = "获取报警列表")
    @GetMapping("/alarm-video")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R getAlarmList(@ApiParam(value = "点位id")@Param("pointId")Long pointId) {
        return R.success(homePageService.getVideoById(pointId));
    }

    //等evs回调
    @ApiOperation(value = "获取报警统计数据", notes = "获取报警统计数据")
    @GetMapping("/statistics")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R<AlarmDTO> getAlarmStatistics() {
        return R.ok((IPage<AlarmDTO>) alarmService.getAlarmStatistics());
    }

    //等evs回调
    @ApiOperation(value = "获取报警趋势数据", notes = "获取报警趋势数据")
    @GetMapping("/trend")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R<AlarmDTO> getAlarmTrend(String startTime, String endTime) {
        return R.success((AlarmDTO) alarmService.getAlarmTrend(startTime, endTime));
    }


    @GetMapping("/getList")
    @ApiOperation(value = "获取组织架构树形结构")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R<List<SysVideoMessage>> getVideoList(@RequestBody(required = false) VideoDto videoDto) {

        R<List<SysVideoMessage>> list = sysVideoMessageService.getList(videoDto);
        // 返回查询结果，表示查询成功
        return R.success(list.getData());
    }

    @ApiOperation(value = "获取所有异常点位参数", notes = "查询并返回所有异常点位信息")
    @GetMapping("/getAllowedParameters")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public R<List<AbnormalPointVo>> getAllowedParameters() {
        List<AbnormalPointVo> result = abnormalPointService.getAllowedParameters();
        return R.success(result);
    }



    @GetMapping("/count")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    @ApiOperation(value = "获取监控统计数据", notes = "返回监控的总数、已配置AI的数量和未配置AI的数量")
    public MonitorStatisticsDTO selectCount() throws Exception {
        return (MonitorStatisticsDTO) sysMonitorStatisticsService.selectCount();
    }

    @GetMapping("/device-count")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    @ApiOperation(value = "根据设备类型获取数据", notes = "返回设备总数、在线设备数量和离线设备数量")
    public List<DeviceStatisticsDto> selectDeviceCount(
            @ApiParam(value ="设备类型")@Param("deviceType")String deviceType
    ) throws Exception {
        return (List<DeviceStatisticsDto>) sysMonitorStatisticsService.selectDeviceCount(deviceType);
    }



    /**
     * 获取视频播放链接
     * 根据监控点位ID、协议类型和时间范围，获取对应的视频播放链接
     * @param pointId  监控点位 ID
     * @param page     当前页码，默认为1
     * @param size     每页显示数量，默认为4
     * @return 返回包含视频播放链接列表的响应对象
     */
    @GetMapping("/getPlaybackLinks")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    @ApiOperation(value = "视频监控", notes = "根据监控点位ID、协议类型和时间范围，获取对应的视频播放链接")
    public R<VideoPlaybackVO> getPlaybackLinks(
            @ApiParam(value = "当前页码", required = false, defaultValue = "1") @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(value = "每页显示数量", required = false, defaultValue = "10") @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(value = "监控点位 ID", required = true) @RequestParam Long pointId,
            @ApiParam(value = "用户id", required = true) @RequestParam Long userId
    ) throws Exception {
        // 调用业务层服务获取视频播放链接分页对象
        IPage<VideoPlaybackVO> playbackLinks = videoPlaybackService.getVideoByUserId(page, size, pointId, userId);

        // 返回包含分页信息的响应对象
        return R.ok(playbackLinks);
    }



    /**
     * 历史监控【根据用户id判断为云端还是本地】
     */
    @ApiOperation(value = "历史监控", notes = "需传入用户id进行判断调取本地还是云端")
    @GetMapping("/historyAlarm")
    @PreAuthorize("hasAuthority('VIEW_VIDEO_MONITOR')")
    public List getHistory(
            @ApiParam(value = "监控点位ID", required = true) @RequestParam Long pointId
            , @ApiParam(value = "起始时间", required = true) @RequestParam String startTime,
            @ApiParam(value = "结束时间", required = true) @RequestParam String endTime,
            @ApiParam(value = "当前页码", required = false, defaultValue = "1") @RequestParam(value = "page", required = false) Integer page,
            @ApiParam(value = "每页显示数量", required = false, defaultValue = "4") @RequestParam(value = "size", required = false) Integer size,
            @ApiParam(value = "用户id", required = true) @RequestParam Long userId
    ) throws Exception {
        return Collections.singletonList(videoPlaybackService.selectVideoHistoryPlaybackRecords(page, size, startTime, endTime, pointId, userId));
    }


}
